package com.njiandan.johnson.vr360library.utils;

import android.content.Context;
import android.opengl.GLES20;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * author：johnsonZhang on 2017/3/17 17:08
 * email：15915356@qq.com
 * 着色器 操作
 */
public class ShaderUtils {
    private static final String TAG = "ShaderUtils";

    /**
     * openg 错误检测
     *
     * @param label 标识
     */
    public static void checkGlError(String label) {
        int error;
        while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {

            throw new RuntimeException(label + ": glError " + error);
        }
    }

    /**
     * 创建着色器程序
     *
     * @param vertexSource   顶点着色器代码
     * @param fragmentSource 片段着色器代码
     * @return int
     */
    public static int createProgram(String vertexSource, String fragmentSource) {
        //1. 加载顶点着色器, 返回0说明加载失败
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
        if (vertexShader == 0) {
            return 0;
        }
        //2. 加载片元着色器, 返回0说明加载失败
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
        if (fragmentShader == 0) {
            return 0;
        }

        //3. 创建着色程序, 返回0说明创建失败
        int program = GLES20.glCreateProgram();
        if (program != 0) {
            //4. 向着色程序中加入顶点着色器
            GLES20.glAttachShader(program, vertexShader);
            checkGlError("glAttachShader");
            //5. 向着色程序中加入片元着色器
            GLES20.glAttachShader(program, fragmentShader);
            checkGlError("glAttachShader");

            //6. 链接程序
            GLES20.glLinkProgram(program);

            int[] linkStatus = new int[1];
            //获取链接程序结果
            GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
            if (linkStatus[0] != GLES20.GL_TRUE) {
                Log.e(TAG, "Could not link program: ");
                Log.e(TAG, GLES20.glGetProgramInfoLog(program));
                //如果链接程序失败删除程序
                GLES20.glDeleteProgram(program);
                program = 0;
            }
        }

        return program;
    }

    /**
     * 加载着色器方法
     *
     * @param shaderType 着色器类型
     * @param source     代码文件
     * @return int
     */
    public static int loadShader(int shaderType, String source) {
        //1.创建一个着色器, 并记录所创建的着色器的id, 如果id==0, 那么创建失败
        int shader = GLES20.glCreateShader(shaderType);
        if (shader != 0) {
            //2.如果着色器创建成功, 为创建的着色器加载脚本代码
            GLES20.glShaderSource(shader, source);
            //3.编译已经加载脚本代码的着色器
            GLES20.glCompileShader(shader);
            int[] compiled = new int[1];
            //4.获取着色器的编译情况, 如果结果为0, 说明编译失败
            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
            if (compiled[0] == 0) {
                Log.e(TAG, "Could not compile shader " + shaderType + ":");
                Log.e(TAG, GLES20.glGetShaderInfoLog(shader));
                //编译失败的话, 删除着色器, 并显示log
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
        }

        return shader;
    }


    public static String readRawTextFile(Context context, int resId) {
        InputStream inputStream = context.getResources().openRawResource(resId);
        return getStringFromStream(inputStream);
    }

    public static String readAssetsTextFile(Context context, String filePath) {
        InputStream inputStream = null;
        try {
            inputStream = context.getResources().getAssets().open(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getStringFromStream(inputStream);
    }

    private static String getStringFromStream(InputStream inputStream){
        if(inputStream==null) return null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            reader.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
